﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.Common;
using Mocola.BLL;
using Mocola.Model;
using System.Collections.Generic;
using System.IO;
/* BEGIN: [#15] */
namespace Mocola.Net.Web
{
    public partial class attachment : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindAttachment();
            }
        }

        private void BindAttachment()
        {
            int id =Int32.Parse(Request.QueryString["id"]);
            string ProjType = Request.QueryString["ProjType"].ToString();
            string FileType = Request.QueryString["FileType"].ToString();
            using (DataTable dt = Databases.MocolaNet.Select(Moc_AttachmentInfo.Moc_Attachment,
                Moc_AttachmentInfo.Moc_Attachment.ID,
                Moc_AttachmentInfo.Moc_Attachment.AttachmentName,
                Moc_AttachmentInfo.Moc_Attachment.Description)
                .Where(Moc_AttachmentInfo.Moc_Attachment.RefID == id & Moc_AttachmentInfo.Moc_Attachment.ProjType == ProjType & Moc_AttachmentInfo.Moc_Attachment.FileType == FileType)
                .ToDataSet().Tables[0])
            {
                listAttachment.DataSource = dt;
                listAttachment.DataBind();
            }
        }

        protected void btnUploadFile_Click(object sender, EventArgs e)
        {
            if (Save())
                BindAttachment();
            else
                Response.Write("上传文件发生错误！");
        }

        private bool Save()
        {
            bool IsResult = true;
            string ProjType = Request.QueryString["ProjType"].ToString();
            string FileType = Request.QueryString["FileType"].ToString();
            int id=Int32.Parse(Request.QueryString["id"]);

            UpLoad file = new UpLoad();
            string folder="";
            if (ProjType == "P")
            {
                if (FileType == "M") //图纸类
                    folder = Server.MapPath(ResolveUrl(ConfigurationManager.AppSettings["UploadPTuZhi"]));
                if (FileType == "F")  //文件类附件
                    folder = Server.MapPath(ResolveUrl(ConfigurationManager.AppSettings["UploadPWenJian"]));
                if (FileType == "O")  //外来文件类附件
                    folder = Server.MapPath(ResolveUrl(ConfigurationManager.AppSettings["UploadPOutWenJian"]));
            }
            else if (ProjType == "M")
            {
                if (FileType == "M") //图纸类
                    folder = Server.MapPath(ResolveUrl(ConfigurationManager.AppSettings["UploadMTuZhi"]));
                if (FileType == "F")  //文件类附件
                    folder = Server.MapPath(ResolveUrl(ConfigurationManager.AppSettings["UploadMWenJian"]));
                if (FileType == "O")  //外来文件类附件
                    folder = Server.MapPath(ResolveUrl(ConfigurationManager.AppSettings["UploadMOutWenJian"]));
            }
            if (!string.IsNullOrEmpty(folder))
            {
                string fileName = file.UpLoadFile(upLoad, folder);
                if (!string.IsNullOrEmpty(fileName))
                {
                    DbTransaction transaction = Databases.MocolaNet.BeginTransaction(IsolationLevel.ReadCommitted);
                    try
                    {
                        int nID = Databases.MocolaNet.Insert(Moc_AttachmentInfo.Moc_Attachment)
                            .AddColumn(Moc_AttachmentInfo.Moc_Attachment.AttachmentName, fileName)
                            .AddColumn(Moc_AttachmentInfo.Moc_Attachment.Description, txtDescrition.Text)
                            .AddColumn(Moc_AttachmentInfo.Moc_Attachment.RefID, id)
                            .AddColumn(Moc_AttachmentInfo.Moc_Attachment.ProjType, ProjType)
                            .AddColumn(Moc_AttachmentInfo.Moc_Attachment.FileType, FileType)
                            .SetTransaction(transaction)
                            .ExecuteReturnAutoIncrementID(Moc_AttachmentInfo.Moc_Attachment.ID);
                        IsResult = nID == -1 ? false : true;
                    }
                    catch
                    {
                        IsResult = false;
                    }
                    finally
                    {
                        if (IsResult)
                            transaction.Commit();
                        else
                            transaction.Rollback();
                    }
                }
                else
                    IsResult = false;
            }
            else
                IsResult = false;
            return IsResult;
        }

        /*Begin:[#18]*/
        protected void listAttachment_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                e.Item.Attributes.Add("OID", DataBinder.Eval(e.Item.DataItem, "ID").ToString());
                e.Item.Attributes.Add("file", DataBinder.Eval(e.Item.DataItem, "attachmentName").ToString());
                string ProjType = Request.QueryString["ProjType"].ToString();
                string FileType = Request.QueryString["FileType"].ToString();
                string fileName = "";
                if (ProjType == "P")
                {
                    if (FileType == "M") //图纸类
                        fileName = ConfigurationManager.AppSettings["UploadPTuZhi"];
                    if (FileType == "F")  //文件类附件
                        fileName = ConfigurationManager.AppSettings["UploadPWenJian"];
                    if (FileType == "O")  //外来文件类附件
                        fileName = ConfigurationManager.AppSettings["UploadPOutWenJian"];
                }
                else if (ProjType == "M")
                {
                    if (FileType == "M") //图纸类
                        fileName = ConfigurationManager.AppSettings["UploadMTuZhi"];
                    if (FileType == "F")  //文件类附件
                        fileName = ConfigurationManager.AppSettings["UploadMWenJian"];
                    if (FileType == "O")  //外来文件类附件
                        fileName = ConfigurationManager.AppSettings["UploadMOutWenJian"];
                }
                fileName += DataBinder.Eval(e.Item.DataItem, "attachmentName").ToString();
                LinkButton btnView = e.Item.FindControl("btnView") as LinkButton;
                if (btnView != null)
                    btnView.OnClientClick = string.Format("OpenAttachment('{0}');return false;", ResolveUrl(fileName));
            }
        }

        protected void btnDel_Click(object sender, EventArgs e)
        {
            //int type = Int32.Parse(Request.QueryString["type"]);
            //string path = string.Empty;
            //if (FileType == "M") //图纸类
            //    path = Server.MapPath(ResolveUrl(ConfigurationManager.AppSettings["UploadTuZhi"]));
            //if (FileType == "F")  //文件类附件
            //    path = Server.MapPath(ResolveUrl(ConfigurationManager.AppSettings["UploadWenJian"]));
            //if (FileType == "O")  //外来文件类附件
            //    path = Server.MapPath(ResolveUrl(ConfigurationManager.AppSettings["UploadOutWenJian"]));
            string ProjType = Request.QueryString["ProjType"].ToString();
            string FileType = Request.QueryString["FileType"].ToString();
            string path = "";
            if (ProjType == "P")
            {
                if (FileType == "M") //图纸类
                    path = Server.MapPath(ResolveUrl(ConfigurationManager.AppSettings["UploadPTuZhi"]));
                if (FileType == "F")  //文件类附件
                    path = Server.MapPath(ResolveUrl(ConfigurationManager.AppSettings["UploadPWenJian"]));
                if (FileType == "O")  //外来文件类附件
                    path = Server.MapPath(ResolveUrl(ConfigurationManager.AppSettings["UploadPOutWenJian"]));
            }
            else if (ProjType == "M")
            {
                if (FileType == "M") //图纸类
                    path = Server.MapPath(ResolveUrl(ConfigurationManager.AppSettings["UploadMTuZhi"]));
                if (FileType == "F")  //文件类附件
                    path = Server.MapPath(ResolveUrl(ConfigurationManager.AppSettings["UploadMWenJian"]));
                if (FileType == "O")  //外来文件类附件
                    path = Server.MapPath(ResolveUrl(ConfigurationManager.AppSettings["UploadMOutWenJian"]));
            }
            List<string> listID = new List<string>();
            foreach (DataListItem item in listAttachment.Items)
            {
                CheckBox chk = item.FindControl("chkItem") as CheckBox;
                if (chk != null && chk.Checked)
                {
                    listID.Add(item.Attributes["OID"]);
                    path+=item.Attributes["file"];
                    DeleteFile(path);
                }
            }
            string sql =string.Format("delete from moc_attachment where id in ({0})",string.Join(",",listID.ToArray()));
            Databases.MocolaNet.ExecuteNonQuery(CommandType.Text,sql);
            BindAttachment();
        }

        private void DeleteFile(string fileName)
        {
            try
            {
                File.Delete(fileName);
            }
            catch
            { }
        }
        /*Begin:[#18]*/
    }
    /*Begin:[#17]*/
    internal class UpLoad
    {
        /// <summary>
        /// 上传文件
        /// 当前文件夹下如有同名文件,则在文件名+1 
        /// </summary>
        /// <param name="file">FileUpload控件</param>
        /// <param name="folder">上传文件目录</param>
        /// <returns>文件名</returns>
        public string UpLoadFile(FileUpload file, string folder)
        {
            HttpPostedFile myFile = file.PostedFile;
            int nFileLen = myFile.ContentLength;
            if (nFileLen > 0)
            {
                string extendName = System.IO.Path.GetExtension(myFile.FileName).ToLower();
                string filter=ConfigurationManager.AppSettings["Filter"];
                if (filter.ToLower().IndexOf(extendName.ToLower()) > 0)
                {
                    byte[] myData = new Byte[nFileLen];
                    myFile.InputStream.Read(myData, 0, nFileLen);
                    string sFilename = System.IO.Path.GetFileName(myFile.FileName);
                    int file_append = 0;
                    //检查当前文件夹下是否有同名文件,有则在文件名+1 
                    while (System.IO.File.Exists(folder + sFilename))
                    {
                        file_append++;
                        sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
                            + file_append.ToString() + extendName;
                    }
                    System.IO.FileStream newFile = new System.IO.FileStream((folder + sFilename), System.IO.FileMode.Create, System.IO.FileAccess.Write);
                    newFile.Write(myData, 0, myData.Length);
                    newFile.Close();
                    return sFilename;
                }
                else
                    return "";
            }
            return "";
        }
    }
    /*End:[#17]*/
}
/* BEGIN: [#15] */